<template>
    <div class="community-list">
        <!-- 页面头部 -->
        <div class="page-header">
            <div class="header-content">
                <h1 class="page-title">社区论坛</h1>
                <p class="page-subtitle">分享知识，交流想法，共同成长</p>
                <el-button 
                    type="primary" 
                    size="large" 
                    @click="goToPublish"
                    class="publish-btn"
                >
                    <el-icon><Edit /></el-icon>
                    发布文章
                </el-button>
            </div>
        </div>

        <!-- 搜索和筛选 -->
        <div class="filter-section">
            <div class="search-bar">
                <el-input
                    v-model="searchQuery"
                    placeholder="搜索文章标题或内容..."
                    size="large"
                    @keyup.enter="handleSearch"
                    class="search-input"
                >
                    <template #prefix>
                        <el-icon><Search /></el-icon>
                    </template>
                    <template #suffix>
                        <el-button type="primary" @click="handleSearch">
                            搜索
                        </el-button>
                    </template>
                </el-input>
            </div>
            
            <div class="filter-tags">
                <el-tag
                    v-for="label in labels"
                    :key="label.id"
                    :type="selectedLabel === label.id ? 'primary' : ''"
                    @click="selectLabel(label.id)"
                    class="filter-tag"
                    effect="plain"
                >
                    {{ label.name }}
                </el-tag>
            </div>
        </div>

        <!-- 文章列表 -->
        <div class="articles-container">
            <div class="articles-grid">
                <div
                    v-for="article in articles"
                    :key="article.id"
                    class="article-card"
                    @click="goToArticle(article.id)"
                >
                    <div class="article-header">
                        <div class="author-info">
                            <el-avatar
                                :size="40"
                                :src="article.user_avatar ? `/file/${article.user_avatar}` : ''"
                            >
                                <el-icon><User /></el-icon>
                            </el-avatar>
                            <div class="author-details">
                                <div class="author-name">{{ article.user_name }}</div>
                                <div class="publish-time">{{ formatTime(article.create_time) }}</div>
                            </div>
                        </div>
                        
                        <div class="article-actions">
                            <el-dropdown>
                                <el-button type="text" size="small">
                                    <el-icon><MoreFilled /></el-icon>
                                </el-button>
                                <template #dropdown>
                                    <el-dropdown-menu>
                                        <el-dropdown-item>收藏</el-dropdown-item>
                                        <el-dropdown-item>分享</el-dropdown-item>
                                        <el-dropdown-item>举报</el-dropdown-item>
                                    </el-dropdown-menu>
                                </template>
                            </el-dropdown>
                        </div>
                    </div>
                    
                    <div class="article-content">
                        <h3 class="article-title">{{ article.title }}</h3>
                        <p class="article-summary">{{ article.digest || article.content }}</p>
                        
                        <div class="article-tags" v-if="article.labels && article.labels.length">
                            <el-tag
                                v-for="label in article.labels"
                                :key="label.id"
                                size="small"
                                class="article-tag"
                            >
                                {{ label.name }}
                            </el-tag>
                        </div>
                    </div>
                    
                    <div class="article-footer">
                        <div class="stats">
                            <span class="stat-item">
                                <el-icon><View /></el-icon>
                                {{ article.page_view || 0 }}
                            </span>
                            <span class="stat-item">
                                <el-icon><ChatDotRound /></el-icon>
                                {{ article.comments || 0 }}
                            </span>
                            <span class="stat-item">
                                <el-icon><Star /></el-icon>
                                {{ article.likes || 0 }}
                            </span>
                        </div>
                        
                        <div class="read-more">
                            <el-button type="primary" text>
                                阅读全文
                                <el-icon><ArrowRight /></el-icon>
                            </el-button>
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- 无限滚动加载更多 -->
            <div 
                v-infinite-scroll="loadMore" 
                class="infinite-scroll-container"
                :infinite-scroll-disabled="loading || !hasMore"
                :infinite-scroll-delay="200"
            >
                <div class="load-more" v-if="loading">
                    <el-button type="primary" loading size="large">
                        加载中...
                    </el-button>
                </div>
                <div class="no-more" v-else-if="!hasMore && articles.length > 0">
                    <el-divider>已经到底了</el-divider>
                </div>
            </div>
            
            <!-- 空状态 -->
            <el-empty v-if="!loading && articles.length === 0" description="暂无文章">
                <el-button type="primary" @click="goToPublish">发布第一篇文章</el-button>
            </el-empty>
        </div>
    </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import {
    Edit,
    Search,
    User,
    MoreFilled,
    View,
    ChatDotRound,
    Star,
    ArrowRight
} from '@element-plus/icons-vue'

import { getArticle, getLabel } from '@/api/community'

const router = useRouter()

// 响应式数据
const articles = ref([])
const labels = ref([])
const loading = ref(false)
const hasMore = ref(true)
const count = ref(0)
const limit = ref(10)
const offset = ref(0)
const searchQuery = ref('')
const selectedLabel = ref(null)

// 初始化数据
const initData = () => {
    articles.value = []
    offset.value = 0
    hasMore.value = true
    fetchArticles(false)
}

// 获取标签列表
const fetchLabels = async () => {
    try {
        const data = await getLabel()
        labels.value = [
            { id: null, name: '全部' },
            ...data
        ]
    } catch (error) {
        console.error('获取标签失败:', error)
    }
}

// 获取文章列表
const fetchArticles = async (append = false) => {
    if (loading.value) return
    
    loading.value = true
    
    try {
        const params = {
            limit: limit.value,
            offset: offset.value
        }
        
        if (searchQuery.value) {
            params.search = searchQuery.value
        }
        
        if (selectedLabel.value) {
            params.label = selectedLabel.value
        }
        
        const data = await getArticle(params)
        console.log('获取到的文章数据:', data)
        console.log('分页信息 - 当前offset:', params.offset, '每页数量:', params.limit, '总数:', data.count)
        
        if (append) {
            articles.value = [...articles.value, ...data.results]
        } else {
            articles.value = data.results || []
        }
        
        count.value = data.count
        console.log('当前文章列表长度:', articles.value.length, '总文章数:', count.value)
        
        // 更新offset用于下次加载
        offset.value = offset.value + limit.value
        
        // 判断是否还有更多数据：只要下次的offset还小于总数，就还有更多
        hasMore.value = offset.value < count.value
        console.log('下次加载offset:', offset.value, '是否还有更多:', hasMore.value, '总数:', count.value)
        
    } catch (error) {
        console.error('获取文章失败:', error)
        ElMessage.error('获取文章失败')
    } finally {
        loading.value = false
    }
}

// 搜索文章
const handleSearch = () => {
    initData()
}

// 选择标签
const selectLabel = (labelId) => {
    selectedLabel.value = labelId
    initData()
}

// 加载更多
const loadMore = () => {
    if (hasMore.value && !loading.value) {
        fetchArticles(true)
    }
}

// 跳转到文章详情
const goToArticle = (articleId) => {
    router.push({ name: 'Community_detail', params: { id: articleId } })
}

// 跳转到发布页面
const goToPublish = () => {
    router.push({ name: 'Article_add' })
}

// 格式化时间
const formatTime = (timeString) => {
    if (!timeString) return '未知时间'
    
    const now = new Date()
    const time = new Date(timeString)
    const diff = now - time
    
    const minutes = Math.floor(diff / (1000 * 60))
    const hours = Math.floor(diff / (1000 * 60 * 60))
    const days = Math.floor(diff / (1000 * 60 * 60 * 24))
    
    if (minutes < 60) {
        return `${minutes}分钟前`
    } else if (hours < 24) {
        return `${hours}小时前`
    } else if (days < 30) {
        return `${days}天前`
    } else {
        return time.toLocaleDateString('zh-CN')
    }
}

onMounted(() => {
    fetchLabels()
    initData()
})
</script>

<style lang="less" scoped>
.community-list {
    padding: 0;
}

.page-header {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    padding: 60px 0;
    margin-bottom: 40px;
    border-radius: 16px;
    position: relative;
    overflow: hidden;
    
    &::before {
        content: '';
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1000 100" fill="rgba(255,255,255,0.1)"><polygon points="1000,100 1000,0 0,100"/></svg>');
        background-size: cover;
    }
    
    .header-content {
        text-align: center;
        position: relative;
        z-index: 1;
        
        .page-title {
            font-size: 48px;
            font-weight: 700;
            margin-bottom: 16px;
            letter-spacing: 2px;
        }
        
        .page-subtitle {
            font-size: 20px;
            opacity: 0.9;
            margin-bottom: 32px;
        }
        
        .publish-btn {
            background: rgba(255, 255, 255, 0.2);
            border: 2px solid rgba(255, 255, 255, 0.3);
            color: white;
            padding: 12px 24px;
            font-size: 16px;
            
            &:hover {
                background: rgba(255, 255, 255, 0.3);
                transform: translateY(-2px);
            }
        }
    }
}

.filter-section {
    margin-bottom: 40px;
    
    .search-bar {
        margin-bottom: 24px;
        
        .search-input {
            :deep(.el-input__wrapper) {
                border-radius: 12px;
                box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
            }
        }
    }
    
    .filter-tags {
        display: flex;
        flex-wrap: wrap;
        gap: 12px;
        
        .filter-tag {
            cursor: pointer;
            padding: 8px 16px;
            border-radius: 20px;
            transition: all 0.3s ease;
            
            &:hover {
                transform: translateY(-2px);
            }
        }
    }
}

.articles-container {
    .articles-grid {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(400px, 1fr));
        gap: 24px;
        margin-bottom: 40px;
    }
    
    .article-card {
        background: white;
        border-radius: 16px;
        padding: 24px;
        cursor: pointer;
        transition: all 0.3s ease;
        box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
        
        &:hover {
            transform: translateY(-4px);
            box-shadow: 0 8px 32px rgba(0, 0, 0, 0.15);
        }
        
        .article-header {
            display: flex;
            align-items: center;
            justify-content: space-between;
            margin-bottom: 16px;
            
            .author-info {
                display: flex;
                align-items: center;
                gap: 12px;
                
                .author-details {
                    .author-name {
                        font-weight: 600;
                        color: #2c3e50;
                        font-size: 14px;
                    }
                    
                    .publish-time {
                        color: #95a5a6;
                        font-size: 12px;
                    }
                }
            }
        }
        
        .article-content {
            margin-bottom: 16px;
            
            .article-title {
                font-size: 20px;
                font-weight: 600;
                color: #2c3e50;
                margin-bottom: 12px;
                line-height: 1.4;
                display: -webkit-box;
                -webkit-line-clamp: 2;
                -webkit-box-orient: vertical;
                overflow: hidden;
            }
            
            .article-summary {
                color: #7f8c8d;
                line-height: 1.6;
                margin-bottom: 16px;
                display: -webkit-box;
                -webkit-line-clamp: 3;
                -webkit-box-orient: vertical;
                overflow: hidden;
            }
            
            .article-tags {
                display: flex;
                flex-wrap: wrap;
                gap: 8px;
                
                .article-tag {
                    background: rgba(102, 126, 234, 0.1);
                    color: #667eea;
                    border: none;
                }
            }
        }
        
        .article-footer {
            display: flex;
            align-items: center;
            justify-content: space-between;
            padding-top: 16px;
            border-top: 1px solid #ecf0f1;
            
            .stats {
                display: flex;
                gap: 16px;
                
                .stat-item {
                    display: flex;
                    align-items: center;
                    gap: 4px;
                    color: #95a5a6;
                    font-size: 14px;
                    
                    .el-icon {
                        font-size: 16px;
                    }
                }
            }
            
            .read-more {
                .el-button {
                    font-weight: 500;
                }
            }
        }
    }
    
    .infinite-scroll-container {
        min-height: 100px;
        padding: 20px 0;
    }
    
    .load-more {
        text-align: center;
        margin-top: 40px;
    }
    
    .no-more {
        text-align: center;
        padding: 20px 0;
        color: #999;
    }
}

/* 响应式设计 */
@media (max-width: 768px) {
    .page-header {
        padding: 40px 20px;
        
        .header-content {
            .page-title {
                font-size: 32px;
            }
            
            .page-subtitle {
                font-size: 16px;
            }
        }
    }
    
    .articles-grid {
        grid-template-columns: 1fr;
    }
    
    .article-card {
        padding: 16px;
    }
    
    .filter-tags {
        .filter-tag {
            padding: 6px 12px;
            font-size: 12px;
        }
    }
}
</style> 